package com.liwt.imageeditor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/** 对图片进行编辑的界面 **/

public class DrawPhoto extends Activity {
	/** 涂鸦控件的容器 **/
	public LinearLayout imageContent;
	/** 操纵图片的路径 **/
	String filePath = "";
	/** 涂鸦控件 **/
	private DrawPhotoView touchView;
	/** 完成按钮 **/
	public TextView overBt;
	/** 完成文字 **/
	public TextView okText;
	/** 重新拍照 **/
	public TextView cameraAgain;
	/** 重拍文字 **/
	public TextView cameraAgainText;
	/** 涂鸦 **/
	public TextView drawPicture;
	/** 涂鸦文字 **/
	public TextView drawText;
	/** 撤销 **/
	public TextView cancelDraw;
	/** 撤销文字 **/
	public TextView cancelText;
	/** 旋转 **/
	// public TextView roatePhoto;
	private Handler handler;
	private ProgressDialog progressDialog = null;
	/** 是否为涂鸦 如果是涂鸦 不能删除之前的照片 **/
	public boolean isReDraw = false;
	Intent intent = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.draw_photo);
		initView();
		// 获取传递过来的图片路径
		intent = getIntent();
		String action = intent.getExtras().getString("action");
		isReDraw = getIntent().getBooleanExtra("ReDraw", false);
		if (action != null && action.equals("takephoto")) {
			Intent takephoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File f = new File(Util.APP_HOME);
			if (!f.exists()) {
				f.mkdir();
			}
			// 设置相机图片输出路径
			takephoto.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(Util.CAMERA_PHOTO)));
			startActivityForResult(takephoto, 1);
		} else {
			filePath = action;
		}
		if (filePath != null && !filePath.equals("")) {
			ImageThread thread = new ImageThread();
			thread.start();
		}
	}

	private void initView() {
		imageContent = (LinearLayout) findViewById(R.id.draw_photo_view);
		handler = new ImageHandler();
		/** 完成按钮 **/
		overBt = (TextView) findViewById(R.id.draw_photo_over);
		okText = (TextView) findViewById(R.id.draw_ok_text);
		/** 重新拍照 **/
		cameraAgain = (TextView) findViewById(R.id.draw_photo_again);
		cameraAgainText = (TextView) findViewById(R.id.draw_photo_re_take_photo);
		/** 涂鸦 **/
		drawPicture = (TextView) findViewById(R.id.draw_photo_draw);
		drawText = (TextView) findViewById(R.id.draw_photo_text);
		/** 撤销 **/
		cancelDraw = (TextView) findViewById(R.id.draw_photo_cancel);
		cancelText = (TextView) findViewById(R.id.draw_photo_cancel_text);

		// 启动涂鸦
		drawPicture.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 可以涂鸦
				if (touchView != null && touchView.getCanDraw()) {
					// 设置不可涂鸦
					touchView.setCanDraw(false);
					drawText.setTextColor(0xffffffff);
				} else {// 设置成可涂鸦
					touchView.setCanDraw(true);
					drawText.setTextColor(0xffd3883a);
				}
			}
		});
		drawText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				drawPicture.performClick();
			}
		});
		// 撤销按钮
		cancelDraw.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelDrawImage();
				drawText.setTextColor(0xffffffff);
			}
		});
		cancelText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				cancelDraw.performClick();
			}
		});

		// 完成
		overBt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				okText.setTextColor(0xff828282);
				overBt.setEnabled(false);
				// 如果读取照片失败 直接关闭
				if (filePath == null && filePath.equals("")) {
					finish();
					return;
				}
				File f = new File(filePath);
				if (!f.exists()) {
					return;
				}
				try {
					if (touchView.srcBitmap != null) {
						touchView.srcBitmap.recycle();
					}
					// 将图片重新存入SD卡
					saveMyBitmap(f, touchView.mBitmap);
					Toast.makeText(DrawPhoto.this, "OK，保存于" + filePath,
							Toast.LENGTH_SHORT).show();
					finish();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
		okText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				overBt.performClick();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 0)// 按返回键 没获取照片
			finish();
		if (requestCode != 1)
			finish();
		if (resultCode == Activity.RESULT_OK && requestCode == 1) {
			// Bitmap bitmap = setImage(uri);
			try {
				BitmapFactory.Options newOpts = new BitmapFactory.Options();
				// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
				newOpts.inPreferredConfig = Bitmap.Config.RGB_565;// 表示16位位图
				newOpts.inInputShareable = true;
				newOpts.inPurgeable = true;// 设置图片可以被回收
				newOpts.inJustDecodeBounds = false;
				// 获取相机返回的数据，并转换为图片格式
				newOpts.inSampleSize = 2;
				Bitmap bitmap = BitmapFactory.decodeFile(Util.CAMERA_PHOTO,
						newOpts);// 读取路径上的文件
				String ddr = Util.IMAGE_PATH;
				File ddrfile = new File(ddr);
				if (!ddrfile.exists()) {
					ddrfile.mkdirs();
				}
				String fileName = Util.IMAGE_PATH + "/"
						+ System.currentTimeMillis() + ".jpg";
				File file = new File(fileName);
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(file));
				// 判断图片是否旋转，处理图片旋转
				ExifInterface exif = new ExifInterface(Util.CAMERA_PHOTO);
				int orientation = exif.getAttributeInt(
						ExifInterface.TAG_ORIENTATION, 0);
				// 处理图片旋转的问题
				Matrix matrix = new Matrix();
				switch (orientation) {
				case 3: {// 旋转了180度
					matrix.setRotate(180);
					bitmap = Bitmap
							.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
									bitmap.getHeight(), matrix, true);
				}
					break;
				case 8: {// 旋转了270度
					matrix.setRotate(270);
					bitmap = Bitmap
							.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
									bitmap.getHeight(), matrix, true);
				}
					break;
				case 6: {// 旋转了90度
					matrix.setRotate(90);
					bitmap = Bitmap
							.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
									bitmap.getHeight(), matrix, true);
				}
				default:
					break;
				}
				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);// 将图片压缩到流中
				bos.flush();// 输出
				bos.close();// 关闭
				bitmap.recycle();// 回收数据
				bitmap = null;
				System.gc(); // 提醒系统及时回收
				filePath = fileName;
				intent.putExtra("action", filePath);
				if (filePath != null && !filePath.equals("")) {
					ImageThread thread = new ImageThread();
					thread.start();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/** 保存图片方法 **/
	public void saveMyBitmap(File f, Bitmap mBitmap) throws IOException {
		try {
			f.createNewFile();
			FileOutputStream fOut = null;
			fOut = new FileOutputStream(f);
			int width = mBitmap.getWidth();
			int height = mBitmap.getHeight();
			// 计算缩放的比例
			int finalWidth = 800;
			int finalHeight = (int) (finalWidth * 1.0 * (height * 1.0 / width * 1.0));
			double x = width * finalHeight;
			double y = height * finalWidth;

			if (x > y) {
				finalHeight = (int) (y / (double) width);
			} else if (x < y) {
				finalWidth = (int) (x / (double) height);
			}

			if (finalWidth > width && finalHeight > height) {
				finalWidth = width;
				finalHeight = height;
			}
			Matrix matrix = new Matrix();
			matrix.reset();
			// 计算宽高缩放率
			float scaleWidth = ((float) finalWidth) / (float) width;
			float scaleHeight = ((float) finalHeight) / (float) height;
			// 缩放图片动作
			matrix.postScale(scaleWidth, scaleHeight);
			mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, (int) width,
					(int) height, matrix, true);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fOut);
			fOut.flush();
			fOut.close();
			// 回收内存空间
			mBitmap.recycle();
			System.gc();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 撤销方法 **/
	public void cancelDrawImage() {
		imageContent.removeAllViews();
		touchView.destroyDrawingCache();
		// 回收以前的内存
		if (touchView.srcBitmap != null) {
			touchView.srcBitmap.recycle();
		}
		if (touchView.mBitmap != null) {
			touchView.mBitmap.recycle();
		}
		WindowManager manager = DrawPhoto.this.getWindowManager();
		int ww = manager.getDefaultDisplay().getWidth();// 这里设置高度
		int hh = manager.getDefaultDisplay().getHeight();// 这里设置宽度为
		touchView = new DrawPhotoView(this, filePath, ww, hh,
				touchView.getColor(), touchView.getNewColor());
		touchView.setLayoutParams(new LayoutParams(touchView.srcBitmap
				.getWidth(), touchView.srcBitmap.getHeight()));
		imageContent.addView(touchView);
	}

	private class ImageHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0:
				progressDialog = ProgressDialog.show(DrawPhoto.this, "图片处理",
						"处理中...");
				break;
			case 1:
				if (touchView != null) {
					// 清除当前界面数据
					imageContent.removeView(touchView);
				}
				touchView.destroyDrawingCache();
				touchView.setLayoutParams(new LayoutParams(touchView.srcBitmap
						.getWidth(), touchView.srcBitmap.getHeight()));
				imageContent.addView(touchView);
				if (progressDialog != null)
					progressDialog.dismiss();
				break;
			case 2:
				// 获取新的图片路径
				filePath = (String) msg.obj;
				// 开启图片和处理线程
				ImageThread thread = new ImageThread();
				thread.start();
				break;
			case 3:
				if (progressDialog != null)
					progressDialog.dismiss();

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	}

	private class ImageThread extends Thread {
		public void run() {
			// 打开进度条
			handler.sendEmptyMessage(0);
			// 获取屏幕大小
			WindowManager manager = DrawPhoto.this.getWindowManager();
			int ww = manager.getDefaultDisplay().getWidth();// 这里设置高度
			int hh = manager.getDefaultDisplay().getHeight();// 这里设置宽度为
			// 生成画图视图
			touchView = new DrawPhotoView(DrawPhoto.this, filePath, ww, hh);
			// 更新界面图片
			Message msg1 = new Message();
			msg1.what = 1;
			handler.sendMessage(msg1);
		}
	}

}
